﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.IO;
using System.Globalization;
using System.Diagnostics;

namespace dmm
{
    //this path to image converter will not keep file open as the .net built-in converter
    //so make it possible to replace the file
    public class PathToImageConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string path = value as string;
            try
            {
                if (path != null)
                {
                    BitmapImage image = new BitmapImage();
                    
                    // using (FileStream stream = File.OpenRead(path))
                    {
                        image.BeginInit();
                        //image.StreamSource = stream;
                        image.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
                        image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                        image.CacheOption = BitmapCacheOption.OnLoad;
                        
                        image.EndInit(); // load the image from the stream
                    } // close the stream
                    return image;
                }
            }
            catch (Exception e)
            {
                Debug.Write(e);
            };
            return null;
        }

         

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }

   
}
